package cc.linker.steplink.crm.service.impl;

import cc.linker.steplink.crm.commons.Constants;
import cc.linker.steplink.crm.commons.RandomCodeGenerator;
import cc.linker.steplink.crm.commons.constant.WebService;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.dao.CrmHelperDao;
import cc.linker.steplink.crm.dao.CustomerDao;
import cc.linker.steplink.crm.dao.UserDao;
import cc.linker.steplink.crm.domain.Customer;
import cc.linker.steplink.crm.domain.User;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchant.service.acs.PageService;
import cc.linker.steplink.crm.response.GlobalException;
import cc.linker.steplink.crm.service.IUserService;
import cc.linker.steplink.crm.service.OauthCheckService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private CustomerDao customerDao;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private OauthCheckService oauthCheckService;
    @Autowired
    private PageService pageService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private CrmHelperDao crmHelperDao;

    @Value("${system.scrm.manageweb}")
    private String managewebUrl;

    @Autowired
    private HttpService httpService;

    @Override
    public void getUser(String usercode) {
        userDao.getUser(usercode);
    }

    @Override
    public User getSimpleUser(String usercode) {
        return userDao.getSimpleUser(usercode);
    }

    @Override
    public Map<String,String> isSaler(String userId) {
        return userDao.isSaler(userId);
    }

    @Override
    public Integer getPayMode(String orgId) {
        return userDao.getPayMode(orgId);
    }

    @Override
    public void savePayModeByOrgId(String orgId,Integer payMode) {
        Integer integer = userDao.countOrgByOrgId(orgId);
        if (integer > 0) {
            userDao.updateOrgByOrgId(orgId,payMode);
        } else {
            userDao.insertOrgByOrgId(orgId,payMode);
        }
    }

    @Override
    public PageInfo getUserPageList(Map<String, Object> param) {
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if (flag) {
            boolean userInterface = systemProperties.isUserInterface();
            if (!userInterface) {
                throw GlobalException.build("暂不开放");
            }
            Integer pageIndex;
            Integer pageSize;
            try {
                pageIndex = (Integer) param.get("pageIndex");
                pageSize = (Integer) param.get("pageSize");
                if (pageIndex == null || pageIndex <= 0) {
                    pageIndex = 1;
                }
                if (pageSize == null || pageSize <= 0) {
                    pageSize = 10;
                }
            } catch (Exception e) {
                throw GlobalException.build("参数错误");
            }
            PageHelper.startPage(pageIndex, pageSize);
            List<Map<String, Object>> userPageList = userDao.getUserPageList(param);
            return new PageInfo<>(userPageList);
        } else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }

    }

    @Override
    public PageInfo getUserBehaviorList(Map<String, Object> param) {
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if (flag) {
            boolean userInterface = systemProperties.isUserInterface();
            if (!userInterface) {
                throw GlobalException.build("暂不开放");
            }
//            if (param.get("customerId") == null) {
//                throw GlobalException.build("缺少参数");
//            }
            Integer pageIndex;
            Integer pageSize;
            try {
                pageIndex = (Integer) param.get("pageIndex");
                pageSize = (Integer) param.get("pageSize");
                if (pageIndex == null || pageIndex <= 0) {
                    pageIndex = 1;
                }
                if (pageSize == null || pageSize <= 0) {
                    pageSize = 10;
                }
            } catch (Exception e) {
                throw GlobalException.build("参数错误");
            }
            if (param.get("customerId") != null) {
                String customerId = param.get("customerId").toString();
                Customer customer = customerDao.selectByPrimaryKey(customerId);
                if (customer == null) {
                    throw GlobalException.build("无此用户");
                }
            }
            PageHelper.startPage(pageIndex, pageSize);
            List<Map<String, Object>> userBehaviorList = userDao.getUserBehaviorList(param);
            return new PageInfo<>(userBehaviorList);
        } else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }
    }

    @Override
    public void alipayUserSave(Map<String, Object> param) {
        String customerId = crmHelperDao.getCustomerIdAlipay(param);
        if (customerId != null && !"".equals(customerId)) {
            //修改
            Map<String, Object> map = new HashMap<>();
            map.put("customerId", customerId);
            if (param.get("nickName") != null) {
                map.put("customerName", param.get("nickName").toString());
            } else {
                throw GlobalException.build("昵称不能为空！");
            }
            crmHelperDao.updateCustomer(map);
        } else {
            //生成customerId
            Map<String, Object> map = new HashMap<>();
            customerId = RandomCodeGenerator.getCustomerId(Constants.CUSTOMER_CODE_SOURCE_WX);
            map.put("customerId", customerId);
            if (param.get("nickName") != null) {
                map.put("customerName", param.get("nickName").toString());
            } else {
                throw GlobalException.build("昵称不能为空！");
            }
            map.put("customerSourceChannel", 7);
            map.put("createUser", "支付宝");
            if (param.get("userCode") != null) {
                User simpUser = userDao.getSimpleUser(param.get("userCode").toString());
                if (simpUser != null) {
                    map.put("orgId", simpUser.getOrgId());
                }
            }
            crmHelperDao.insertCustomer(map);

            Map<String, Object> temp = new HashMap();
            temp.put("customerInfoId", UUID.randomUUID().toString());
            temp.put("customerId", customerId);
            crmHelperDao.insertCustomerInfo(temp);

            param.put("customerId", customerId);
            crmHelperDao.insertCustomerAlipay(param);
        }

    }

    @Override
    public boolean isApp(String orgId) {
        String appId = userDao.getAppIdByOrgId(orgId);
        return !StringUtils.isEmpty(appId);
    }


    @Override
    public void appUserSave(Map<String, Object> param) {
        if( param.get("appId") != null){
            String appId = param.get("appId").toString();
            String orgId = crmHelperDao.getOrgIdByAppId(appId);
            if(!StringUtils.isEmpty(orgId)){
                param.put("orgId",orgId);
            }else {
                throw GlobalException.build("该app未被绑定！");
            }
        }else {
            throw GlobalException.build("appId不能为空！");
        }
        String customerId = crmHelperDao.getCustomerIdApp(param);
        if (customerId != null && !"".equals(customerId)) {
            //判断是否有修改
            Integer count = crmHelperDao.getCustomerIdAppCount(param);
            if(count!=null && count==0){
                //修改
                Map<String, Object> map = new HashMap<>();
                map.put("customerId", customerId);
                if (param.get("nickName") != null) {
                    map.put("customerName", param.get("nickName").toString());
                } else {
                    throw GlobalException.build("昵称不能为空！");
                }
                crmHelperDao.updateCustomer(map);
                crmHelperDao.updateCustomerApp(param);
            }
        } else {
            //生成customerId
            Map<String, Object> map = new HashMap<>();
            customerId = RandomCodeGenerator.getCustomerId(Constants.CUSTOMER_CODE_SOURCE_WX);
            map.put("customerId", customerId);
            if (param.get("nickName") != null) {
                map.put("customerName", param.get("nickName").toString());
            } else {
                throw GlobalException.build("昵称不能为空！");
            }
            map.put("customerSourceChannel", 6);
            map.put("createUser", "app");
            if (param.get("orgId") != null) {
                 map.put("orgId", param.get("orgId").toString());
            }
            if (param.get("icon") != null) {
                map.put("customerAvatar", param.get("icon").toString());
            }
            if (param.get("phone") != null) {
                map.put("customerPhone", param.get("phone").toString());
            }
            crmHelperDao.insertCustomer(map);

            Map<String, Object> temp = new HashMap();
            temp.put("customerInfoId", UUID.randomUUID().toString());
            temp.put("customerId", customerId);
            crmHelperDao.insertCustomerInfo(temp);

            param.put("customerId", customerId);
            crmHelperDao.insertCustomerApp(param);
        }

    }

    @Override
    public Integer getPayModeByUserCenter(String orgId) {
        //
        String result = "";
        try{
            String url = managewebUrl+ WebService.USERWEBAPI_API_ORG_BASE+"?orgcode="+orgId;
            result = httpService.doGet(url);
        }catch (Exception e){
            LOGGER.info("getPayModeByUserCenter_error_<--"+orgId+"-->:"+e.getMessage());
            return 1;
        }
        LOGGER.info("getPayModeByUserCenter_result_<--"+orgId+"-->:_<--"+result+"-->");
        if (!StringUtils.isEmpty(result)) {
            Map parse = (Map) JSON.parse(result);
            if((Integer) parse.get("retcode") == 0){
                Map map = (Map) parse.get("retobj");
                if(map==null){
                    return 0;
                }
                if(map.containsKey("paymode")){
                    return Integer.valueOf(map.get("paymode").toString());
                }
            }
        }
        return 1;
    }

    /**
     * 初始化数据
     * @param user
     */
    @Override
    public void setInitialize(User user){
        // 初始化
        String orgId = user.getOrgId();
        String adminId = user.getAdminId();
        String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
        if(StringUtils.isEmpty(customerId)){
            customerId = orgId;
        }

        pageService.setInitializePage(customerId,orgId);
    }

    @Override
    public List getVipListByCustomerId(String customerId) {
        return crmHelperDao.getVipListByCustomerId(customerId);
    }

    @Override
    public Customer getUserInfo(Map<String, Object> param) {
        String token = "";
        if (param.get("token") != null && param.get("token") != "") {
            token = param.get("token").toString();
        } else {
            throw GlobalException.build("请传正确的token！");
        }
        Boolean flag = oauthCheckService.checkOauth(token);
        if (flag) {
            boolean userInterface = systemProperties.isUserInterface();
            if (!userInterface) {
                throw GlobalException.build("暂不开放");
            }
            if (param.get("customerId") != null) {
                String customerId = param.get("customerId").toString();
                Customer customer = customerDao.selectByPrimaryKey(customerId);
                if (customer == null) {
                    throw GlobalException.build("无此用户");
                }
                return customer;
            }else {
                throw GlobalException.build("参数错误");
            }
        } else {
            throw GlobalException.build("token未激活或已过期，请传正确的token！");
        }

    }
}
